package tr.edu.yildiz.ce.dap.appagent.service;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import tr.edu.yildiz.ce.dap.appagent.exception.AgentMessageException;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.model.XMLModel;
import tr.edu.yildiz.ce.dap.appagent.util.AppAgentHandler;

public class MessageConverter {
    
    
    public static String convertToXML(Object obj){
        return ((XMLModel) obj).toXML();
    }
    
    
    public static DapMessage convertToObject(String xmlString) throws AgentMessageException{
    	try {
    		SAXParserFactory spf = SAXParserFactory.newInstance();
    		SAXParser sp = spf.newSAXParser();
    		XMLReader xr = sp.getXMLReader();
    		AppAgentHandler myXMLHandler = new AppAgentHandler();
    		xr.setContentHandler(myXMLHandler);
    		xr.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes())));
    		return myXMLHandler.getDapMessage();
    	}catch (Exception e) {
			throw new AgentMessageException(e);
		}
    }
    
    
}
